package com.csdj.rest.controller;

import com.csdj.beans.entity.Order;
import com.csdj.beans.interfaces.order.IOrderService;
import com.csdj.common.WebResult;
import com.csdj.common.constant.CommonConstant;
import com.csdj.common.constant.WebResultConstant;
import com.csdj.common.utils.JsonUtil;
import com.csdj.middleware.RocketMqProducer;
import com.csdj.middleware.ZookeeperService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.session.TooManyActiveSessionsException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("order")
public class OrderController {

    @Resource
    private ZookeeperService zookeeperService;

//    @DubboReference
    private IOrderService orderService;

//    @Resource
    private RocketMqProducer rocketMqProducer;

    @Value("${mq.rocket.producer.topic}")
    private String topic;

    @PostMapping("/add")
    public WebResult addOrder(String path){
        //查询商品信息
//        总数量，商品名称，zooPath
        String zooPatah = "/zoo/order/phone";
        int total = 20;
        try {
            if(zookeeperService.getOrderPermit(path, total)){
                System.out.println("进行下单操作");
                return new WebResult(200,"下单成功");
            }else{
                System.out.println("库存不足");
                return new WebResult(201,"库存不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("zookeeper 操作异常");
            return new WebResult(500,"操作异常");
        }
    }

    @PutMapping("/new")
    public WebResult createOrder(@RequestParam("prodId")int prodId,
                                 @RequestParam("quanitity")int quanitity,
                                 @RequestParam("points")int points,
                                 HttpServletRequest request){
        String userIdStr = request.getHeader(CommonConstant.HEADER_USER_ID);
        //检查余额， 积分， 库存
        final Order order = orderService.generate(Integer.parseInt(userIdStr), prodId, quanitity,points);
        if(order != null){
            //订单创建成功， 发送延迟消息，10分钟后如果没有支付则取消订单
            ObjectMapper ob = new ObjectMapper();
            rocketMqProducer.sendDelay(topic,CommonConstant.MQ_TAGS_ORDER_CHECK, order.getId()+"",5);
            return WebResult.success(order);
        }
        return WebResult.fail(WebResultConstant.ORDER_FAIL);
    }
}
